package light.head.controller.inv;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Url;
import light.head.dao.inv.InvInStorageDAO;
import light.head.dao.inv.InvInStorageDetailDAO;
import light.head.dao.inv.InvInStorageItemDAO;
import light.head.dao.sys.OrganDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.DateUtils;
import light.head.model.inv.InvInStorage;
import light.head.model.inv.InvInStorageDetail;
import light.head.model.inv.InvInStorageItem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value = Url.C_INVINSTORAGE)
public class InvInStorageController extends SupporterController{
	
	private InvInStorageDAO iisDAO;
	private InvInStorageItemDAO itemDAO;
	private InvInStorageDetailDAO detailDAO;
	private OrganDAO organDAO;
	
	private final static String sheetName = "入库导出";
	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.INVINSTORAGE_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.DN,Parm.CNAME, Parm.DELETED, Parm.TIME1, Parm.TIME2,Parm.CN,Parm.BNAME);
		if (iisDAO.findByMap(organDAO.getSonCodeList(cu_organCode(request)), map, pb) == RESULT.SUCCESS){
			InvInStorage iis =null;
			for (Object o : pb.getResultList()) {
				iis = (InvInStorage) o;
				iis.setItemList(itemDAO.findIisc(iis.getCode()));
			}
		}
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.INVINSTORAGE_LIST);
	}
	
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if (null != code) {
			InvInStorage iis = iisDAO.get(Integer.parseInt(code));
			List<InvInStorageItem> itemList = itemDAO.findIisc(iis.getCode());
			iis.setItemList(itemList);
			for (InvInStorageItem item : itemList) {
				List<InvInStorageDetail> detailList = detailDAO.findIisic(item.getCode());
				item.setDetailList(detailList);
			}
			request.setAttribute(Parm.INVINSTORAGE, iis);
		} 
		return new ModelAndView(Url.INVINSTORAGE_DETAIL);
	}
	@RequestMapping(value = Url.SHIELD)
	public void shield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		InvInStorage de = iisDAO.get(Integer.parseInt(code));
		if (null == de) {
			print(response, Msg.NOT_FIND);
			return;
		}
		de.setDeleted(true);
		if (iisDAO.upd(de) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(value = Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		InvInStorage de = iisDAO.get(Integer.parseInt(code));
		if (null == de) {
			print(response, Msg.NOT_FIND);
			return;
		}
		de.setDeleted(false);
		if (iisDAO.upd(de) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}
	
	@RequestMapping(Url.EXCEL)
	public void exportExcel(String bname,String time1,String time2, HttpServletRequest request, HttpServletResponse response) throws Exception{
		Integer oc =organDAO.getRoot(cu_organCode(request)).getCode();
		List<InvInStorage> list = iisDAO.findCode(organDAO.getSonCodeList(oc),bname,time1,time2);
		for (InvInStorage iis : list) {
			iis.setItemList(itemDAO.findIisc(iis.getCode()));
		}
			/**** 构造Excel文件 ****/
			response.reset();
			OutputStream os = response.getOutputStream();
			WritableWorkbook workbook = Workbook.createWorkbook(os);
			WritableSheet sheet = workbook.createSheet(sheetName, 0);

			// 单元格样式，用于标题
			WritableFont fnFont = new WritableFont(WritableFont.createFont("宋体"), 9, WritableFont.BOLD);
			WritableCellFormat wcf_title = new WritableCellFormat(fnFont);
			wcf_title.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
			wcf_title.setVerticalAlignment(VerticalAlignment.CENTRE);				// 垂直对齐
			wcf_title.setAlignment(Alignment.CENTRE);
			wcf_title.setWrap(true);												// 是否换行

			// 单元格样式，用于普通内容
			WritableFont fFont = new WritableFont(WritableFont.createFont("宋体"), 9);
			WritableCellFormat wcf_center = new WritableCellFormat(fFont);
			wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
			wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE);				// 垂直对齐
			wcf_center.setAlignment(Alignment.LEFT);
			wcf_center.setWrap(true);												// 是否换行

			// 单元格样式，用于无库存内容
			WritableFont noStockFont = new WritableFont(WritableFont.createFont("宋体"), 9, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLUE2);
			WritableCellFormat no_stock_center = new WritableCellFormat(noStockFont);
			no_stock_center.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
			no_stock_center.setVerticalAlignment(VerticalAlignment.CENTRE);				// 垂直对齐
			no_stock_center.setAlignment(Alignment.LEFT);
			no_stock_center.setWrap(true);												// 是否换行

			// 单元格样式，用于价格内容
			WritableFont noPriceFont = new WritableFont(WritableFont.createFont("宋体"), 9, WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.RED);
			WritableCellFormat no_price_center = new WritableCellFormat(noPriceFont);
			no_price_center.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
			no_price_center.setVerticalAlignment(VerticalAlignment.CENTRE);				// 垂直对齐
			no_price_center.setAlignment(Alignment.LEFT);
			no_price_center.setWrap(true);												// 是否换行
			
			//表头
			sheet.setColumnView(0, 25);
			sheet.addCell(new Label(0, 0, "来往商名称", wcf_title));
			sheet.setColumnView(1, 12);
			sheet.addCell(new Label(1, 0, "入库时间", wcf_title));
			sheet.setColumnView(2, 10);
			sheet.addCell(new Label(2, 0, "创建人", wcf_title));
			sheet.setColumnView(3, 40);
			sheet.mergeCells(3, 0, 6, 0);
			sheet.addCell(new Label(3, 0, "明细(商品/数量/单位/金额)", wcf_title));
			int x = 0;
			int y = 0;
			int index = 0;
			for(int i = 0; i < list.size(); i++){
				List<InvInStorageItem> itemList = list.get(i).getItemList();
				index = itemList.size();
				sheet.mergeCells(0, x + 1, 0, x + index);
				sheet.mergeCells(1, x + 1, 1, x + index);
				sheet.mergeCells(2, x + 1, 2, x + index);
				
			SimpleDateFormat dateformat1=new SimpleDateFormat("yyyy-MM-dd");
				sheet.addCell(new Label(0, x + 1, list.get(i).getBname(), wcf_center));
				sheet.addCell(new Label(1, x + 1, dateformat1.format(list.get(i).getCt()), wcf_center));
				sheet.addCell(new Label(2, x + 1, list.get(i).getCn().toString(), wcf_center));
				for(int j = 0; j < itemList.size(); j ++){
					sheet.addCell(new Label(3, y + j + 1, itemList.get(j).getCname().toString(), wcf_center));
					sheet.addCell(new Label(4, y + j  + 1, itemList.get(j).getNumber().toString(), wcf_center));
					sheet.addCell(new Label(5, y + j  + 1, itemList.get(j).getUn().toString(), wcf_center));
					sheet.addCell(new Label(6, y + j  + 1, itemList.get(j).getPrice().toString(), wcf_center));
				}
				x = x + index;
				y = y + index;
			}
			String fileName = "入库记录表(" + DateUtils.getDateStr(new Date(), DateUtils.yyyy_MM_dd) + ").xls";
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/msexcel; charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "ISO8859_1"));
			workbook.write();
			workbook.close();
			os.flush();
			os.close();
	}
	@Autowired
	public void setIisDAO(InvInStorageDAO iisDAO) {
		this.iisDAO = iisDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	@Autowired
	public void setItemDAO(InvInStorageItemDAO itemDAO) {
		this.itemDAO = itemDAO;
	}
	@Autowired
	public void setDetailDAO(InvInStorageDetailDAO detailDAO) {
		this.detailDAO = detailDAO;
	}
	
}
